/*
 * alarmclock_main.c
 *
 *  Created on: 2013-6-29
 *      Author: yangyang
 */

/*INCLUDES *******************************************************************/
#include "ses_button.h"
#include "ses_buzzer.h"
#include "ses_lcd.h"
#include "ses_lcdDriver.h"
#include "ses_led.h"
#include "ses_scheduler.h"
#include "ses_timer.h"
#include "ses_alarmclock.h"

/*MACROS*****************************************************************/
#define EXPIREBUZZ 			30000		// 30s expire period time for Buzzer
#define PERIODBUZZ 			0
#define EXPIRE_DISPATCH  	100			// 100ms expire Dispatch time
#define PERIOD_DISPATCH  	100			// 100ms period Dispatch time
#define EXPIRE_CHECKTIME  	100			// 100ms expire Check time
#define PERIOD_CHECKTIME  	100			// 100ms period Check time
/*GLOABLE TYPE**************************************************************/
struct type_timeRTC time;
struct type_timeRTC real;
struct type_timeRTC sdft;
Fsm clockfsm;
Event clockevent;

/*FUNCTION DECLEARION*******************************************************/
void assignJoy();
void assignRot();
void wait30s();
void checktime();
void scheduler_fsmdispatch();

/*MAIN*********************************************************************/

// Main function
int main(void) {

	// Initialize FSM
	fsminit(&clockfsm, alarmclock_init);

	// Set Buttons Interrupts to execute: assignJoy / assignRot
	button_setJoystickButtonCallback(assignJoy);
	button_setRotaryButtonCallback(assignRot);

	// add checking Time function to scheduler
	scheduler_add(checktime, EXPIRE_CHECKTIME, PERIOD_CHECKTIME);

	// add FSM dispatching to scheduler
	scheduler_add(scheduler_fsmdispatch, EXPIRE_DISPATCH, PERIOD_DISPATCH);

	// Run scheduler
	scheduler_run();

	return 0;

}

// check to see if Alarm Clock Time is equal to Real Time clock
void checktime() {

	if (clockfsm.alarmSet == 1) {

		struct type_timeRTC alarmrtc, realtime;

		scheduler_getTimeRTC(&realtime);
		ms_convertTime(clockfsm.timeSet, &alarmrtc);

		/*
		 * Check if alarm clock Time is equal to Real Time, then set the Buzzer ON
		 * by setting Clock Signal to "TIME_OUT"
		 */
		if (((alarmrtc.hour) == realtime.hour)
				&& (alarmrtc.minute == realtime.minute)) {

			setflag();
			clockevent.signal = TIME_OUT;
			scheduler_add(wait30s, EXPIREBUZZ, PERIODBUZZ);
		}

	}

}

// Set Clock Event signal to: JOYSTICK_BUTTON
void assignJoy() {
	setflag();
	clockevent.signal = JOYSTICK_BUTTON;
}

// Set Clock Event signal to: ROTARY_BUTTON
void assignRot() {
	setflag();
	clockevent.signal = ROTARY_BUTTON;
}

// dispatching FSM by setting clock FSM's and Events
void scheduler_fsmdispatch() {
	fsmdispatch(&clockfsm, &clockevent);
}

// Set Clock Event signal to: WAIT_30S
void wait30s() {
	setflag();
	clockevent.signal = WAIT_30S;
}

